<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ include file="/public/header.jsp"%>
<%
    String callback = request.getParameter("callback");
	String isShow = request.getParameter("isShow") == null ? "" : request.getParameter("isShow");
	String id = request.getParameter("id") == null ? "" : request.getParameter("id");	
	Map<String, Object> sessionMap = (Map<String, Object>) session.getAttribute("LOGIN_USER");
	String person_id = String.valueOf(sessionMap.get("id"));
	String person = String.valueOf(sessionMap.get("truename"));
	
    boolean isAdd = "".equals(id);
    int flag = 0;
    if(!isAdd){
    	flag = 1;
    }

%>
<html>
	<head>
		<title><%=isAdd?"新建项目报账单":"编辑项目报账单" %></title>
		<link href="<%=contextPath%>/public/css/smart_wizard_vertical.css" rel="stylesheet"	type="text/css">
		<script type="text/javascript" src="<%=contextPath%>/public/js/jquery.smartWizard.js"></script>
		<link  rel="stylesheet"  href  ="<%=contextPath%>/public/swfupload/css/swfupload.css">
	
		<style>
			.td1{
				padding-top:10px;
				padding-bottom:5px;
				font-size: 12px;
				background-color: #c0ebd7;
				width:20%;
			}
			.td2{
				padding:5px;
			}
			.tdg{
			padding-top:10px;
			padding-bottom:5px;
			font-size: 12px;
			background-color: #c0ebd7;
			width:20%;
		}
		.tdb{
			padding:5px;
			width:30%;
		}
		</style>
		  <script  type="text/javascript"  src="<%=contextPath%>/core/js/datastructs.js"  ></script>
			<script  type="text/javascript"  src="<%=contextPath%>/core/js/sys.js"  ></script>
			<script  type="text/javascript"  src="<%=contextPath%>/core/js/prototype.js"  ></script>
		<script type="text/javascript" src="<%=contextPath%>/public/swfupload/js/attachMenu.js"></script>
		<script type="text/javascript" src="<%=contextPath%>/public/swfupload/js/Menu.js"></script>
		<script  type="text/javascript"  src="<%=contextPath%>/public/swfupload/js/swfupload.js"  ></script>
		<script  type="text/javascript"  src="<%=contextPath%>/public/swfupload/js/fileprogress.js"  ></script>
		<script  type="text/javascript"  src="<%=contextPath%>/public/swfupload/js/handlers.js"  ></script>
		<script  type="text/javascript"  src="<%=contextPath%>/public/swfupload/js/swfupload.queue.js"  ></script>
   		 
		<script type="text/javascript">
		var lastIndex;
		var flag="<%=flag%>";
		jQuery(document).ready(function() {
			if(flag == '1'){
				jQuery('#lv').form({
					onLoadSuccess:function(){
						queueCompleteOver();
					}
				});
					
			
			}else{
				jQuery("#operation_time").datetimebox('setValue',getTodaySecond());
			}
			<%=isAdd?"":"jQuery('#lv').form('load','"+contextPath+"/springMVC/xmFinance/getReimbursementById?rem_id="+id+"');"%>
			jQuery("#table").datagrid({
				title:"员工借款",
				iconCls:'icon-zc',
				loadMsg:'正在加载数据，请稍后......',
				<%=isAdd?"url:'',":"url:'"+contextPath+"/springMVC/xm/listPageXmReimDetail?rem_id="+id+"',"%>
				rownumbers:true,
				fitColumns:true,
				idField:'id',
				frozenColumns:[[
				      {field:'ck',checkbox:true},
				      {title:'主键',field:'id',hidden:true},
				      {title:'报账id',field:'rem_id',hidden:true},
				      {title:'借款单id',field:'loan_id',hidden:true}
				]],
				columns:[[
					{title:'工单编号',field:'gd_code',width:100,align:'center'},
					{title:'工单名称',field:'gd_name',width:100,align:'center'},
					{title:'放款日期',field:'actual_operation_date',width:100,align:'center',sort:true},
					{title:'借款人',field:'person_name',width:100,align:'center'},
					{title:'借款金额',field:'loan_money',width:100,align:'center'},
					{title:'报账金额',field:'money',width:100,align:'center',editor:{
						type:'numberbox',
						options:{
							min:0,
							precision:2
						}
					}}
				]],
				pageSize:10,
				pageList : [10,50,100],  
				pagination:true,
				onBeforeLoad:function(){
					jQuery(this).datagrid('rejectChanges');
				},
				onAfterEdit:function(rowIndex, rowData, changes){
					   reimMoney();
					},
				onClickCell:function(rowIndex,field,value){
					if (lastIndex != rowIndex){
						jQuery('#table').datagrid('endEdit', lastIndex);
						jQuery('#table').datagrid('beginEdit', rowIndex);
						var ed = jQuery('#table').datagrid('getEditor', {index:rowIndex,field:field});
						if(ed == null){
							ed = jQuery('#table').datagrid('getEditor', {index:rowIndex,field:'out_invoice'});
						}
						jQuery(ed.target).select();
					}
					lastIndex = rowIndex;
				},
				toolbar:[
					{
						id:'add',
						text:'选择借款单',
						disabled:false,
						iconCls:'icon-add',
						handler:function(){
							  var xm_id = jQuery('#xm_id').val();
							  if(xm_id==""){
								  jQuery.messager.alert('提示：','请先选择项目!!');
								  return false;
							  }
							  openWindow('<%=contextPath %>/springViews/xm/gdSetSelectByLoan.jsp?xm_id='+xm_id,"借款单选择",1000, 800);
						}
					},'-',{
					id:'save',
					text:'保存修改',
					disabled:false,
					iconCls:'icon-save',
					handler:function(){
						jQuery('#table').datagrid('acceptChanges');
						lastIndex =-1;
					}
					},'-',{
					id:'delete',
					text:'删除',
					disabled:false,
					iconCls:'icon-remove',
					handler:function(){
						jQuery('#table').datagrid('acceptChanges');
						lastIndex =-1;
						var rows = jQuery('#table').datagrid('getSelections');
						if (rows.length > 0){
							for(var i=0;i<rows.length;i++){
								var row = rows[i];
								var index = jQuery('#table').datagrid('getRowIndex', row);
								jQuery('#table').datagrid('deleteRow', index);
							}
						}
						var data = jQuery('#table').datagrid('getData');
						jQuery('#table').datagrid('loadData',data);
					}
				}
			   ],
				onLoadSuccess:function(rtJson){
					if(rtJson.rtState== '1')
					{
						jQuery.messager.alert('提示',rtJson.rtMsrg);
					}
				}
			});
			
			
			 var settings = {
				      flash_url : "<%=contextPath%>/public/swfupload/swfupload.swf",
				      upload_url: "<%=contextPath%>/springMVC/fileUpload/fileupload",
				      post_params: {
				    	 "module" : "<%=com.beaut.project.util.StaticData.GD_MODULE%>"
				      },
				      file_size_limit : "100 MB",
				      file_types : "*.*",
				      file_types_description : "All Files",
				      file_upload_limit : 100,
				      file_queue_limit : 0,
				      custom_settings : {
				        uploadArea : "fsUploadArea",
				        progressTarget : "fsUploadProgress",
				        startButtonId : "btnStart",
				        cancelButtonId : "btnCancel"
				      },
				      debug: false,
				      button_image_url: "<%=contextPath%>/public/swfupload/img/uploadx4.gif",
				      button_width: "65",
				      button_height: "29",
				      button_placeholder_id: "spanButtonUpload",
				      button_text: '<span class=\"textUpload\">上传附件</span>',
				      button_text_style: ".textUpload{color:#0000ff;}",
				      button_text_top_padding : 1,
				      button_text_left_padding : 18,
				      button_width: 80,
				      button_height: 20,
				      button_window_mode: SWFUpload.WINDOW_MODE.TRANSPARENT,
				      button_cursor: SWFUpload.CURSOR.HAND,
				      
				      file_queued_handler : fileQueued,
				      file_queue_error_handler : fileQueueError,
				      file_dialog_complete_handler : fileDialogComplete,
				      upload_start_handler : uploadStart,
				      upload_progress_handler : uploadProgress,
				      upload_error_handler : uploadError,
				      upload_success_handler : uploadSuccessOver,
				      upload_complete_handler : uploadComplete,
				      queue_complete_handler : queueCompleteOver
				    };
				    swfupload = new SWFUpload(settings);
				  
				});
			
		 function uploadSuccessOver(file, serverData){
				  try {
				    var progress = new FileProgress(file, this.customSettings.progressTarget);
				    progress.toggleCancel(false);
				    var json = null;
				    json = serverData.evalJSON();
				    if(json.rtState=="1") {
				       progress.setError();
				       progress.setStatus("上传失败");
				    } else {
				       if($('attachmentId').value!=null && $('attachmentId').value!=""){
				    	 $('attachmentId').value += ',' + json.rtData.attachmentId;
				       } 
				       else{
				    	   $('attachmentId').value = json.rtData.attachmentId;
				       }
				       if($('attachmentName').value!=null && $('attachmentName').value!=""){
				    	 $('attachmentName').value += '*' + json.rtData.attachmentName;
				       } 
				       else{
				    	   $('attachmentName').value = json.rtData.attachmentName;
				       }
				    }
				  } catch (ex) {
				    this.debug(ex);
				  }
		}
		function queueCompleteOver(){
			var attachmentIds = $("attachmentId").value;
		    var attachmentNames = $("attachmentName").value;
		    if(attachmentIds){
		      jQuery('#attaTr').show();
	       	  jQuery('#fsUploadArea').hide();
	       	  if("<%=isShow%>"==1){
		       	  attachMenuUtil("showAtt",null,null,attachmentNames,attachmentIds,true,'attach');
	       	  }else{
		       	  attachMenuUtil("showAtt",null,null,attachmentNames,attachmentIds,false,'attach');
	       	  }
		    }
		 }
				 
		  function deleteAttachment(attachmentId,attachmentName){
			  var attrIds = $("attachmentId").value;
		    var attrNames = $("attachmentName").value;
		     var attrIdArrays = attrIds.split(",");
			  var attrNameArrays = attrNames.split("*");
			 var idArray = new Array();
			 var nameArray = new Array();
			 
			 for(var i=0;i<attrIdArrays.length;i++){
				 if(attrIdArrays[i] != attachmentId){
					 idArray.push(attrIdArrays[i]);
					 nameArray.push(attrNameArrays[i]);
				 }
			 }
			 $("attachmentId").value = idArray.join(",");
			 $("attachmentName").value = nameArray.join("*");
			 if($("attachmentId").value == ""){
				 jQuery('#attaTr').hide();
			 }
		  }
		  
		 
			function doSubmit(obj){
				jQuery('#table').datagrid('acceptChanges');
				var moneys=0;
				var loan_moneys=0;
				lastIndex =-1;
				if(jQuery('#ff').form('validate')){
					var products="";
					var jsondata=jQuery("#table").datagrid("getData");
					for(var i=0;i<jsondata.total;i++){
						if(products!=""){
							products+=";";
						}
						products+=jsonToStr(jsondata.rows[i]);
						moneys+=parseFloat(jsondata.rows[i].money);
						loan_moneys+=parseFloat(jsondata.rows[i].loan_money);
					}
				}
				jQuery("#reimbursement").numberbox("setValue",moneys);
				jQuery("#loan_money").numberbox("setValue",loan_moneys);
				if(parseFloat(moneys)<0){
					jQuery.messager.alert("提示","报销金额不能小于0，请重新输入");
					return ;
				}
				var attachmentIds = $("attachmentId").value;
				if(!checkNullOREmpty(attachmentIds,'请上传报账单据，报账单据必传项！')){return;}
				jQuery("#lv").form('submit',{
					url:"<%=contextPath %>/springMVC/xmFinance/<%=isAdd ? "addXMReimbursement" : "updateXMReimbursement?id=" + id%>",
					queryParams:{"products":products,"is_borrow":"1"},
					onSubmit:function(){
						var isValid = jQuery(this).form('validate');
						if(isValid){
							jQuery(obj).hide();
						}
						return isValid;
					},
					success:function(rtJson){
						rtJson = eval('(' + rtJson + ')'); 
						if (rtJson.rtState == '0'){
							warningInfo(rtJson.rtMsrg);
							if(flag!=1){
								eval('parent.window.opener.rtCallBack();');
								parent.window.close();
								}else{
									eval('window.opener.rtCallBack();');
									window.close();
								}
							
						}else{
							jQuery(obj).show();
							warningInfo(rtJson.rtMsrg);
						}
					}
				});
			}

		    function choseXm(){
		    	openWindow("<%=contextPath %>/springViews/xm/choseMyXM.jsp?statusType=4","项目选择",1000, 800);
		    	
		    }
			function rtCallBackXmSet(xm_id,xm_code,xm_name,a,b,c,d){
				 jQuery("#xm_id").val(xm_id);
			     jQuery("#xm_name").val(xm_name);
			     jQuery("#xm_code").val(xm_code);
			}
			function addRows(ids,sumMoneys,gd_codes,gd_names,person_names,actual_operation_dates,moneys){
				
				 if(ids==""){
					  return;
				 }
				 var idArray= new Array();
				 var gdCodeArray= new Array();
				 var gdNameArray= new Array();
				 var moneysArray= new Array();
				 var person_nameArray= new Array();
				 var actual_operation_datesArray= new Array();
				 idArray=ids.split(",");
				 gdCodeArray=gd_codes.split(",");
				 gdNameArray=gd_names.split(",");
				 person_nameArray=person_names.split(",");
				 actual_operation_datesArray=actual_operation_dates.split(",");
				 moneysArray=moneys.split(",");
				
				 jQuery('#table').datagrid('acceptChanges');
				lastIndex =-1;
				var moneys=0;
				var loan_money=0;
			     var jsondata=jQuery("#table").datagrid("getData");
			     for (var i=0;i<idArray.length ;i++ )   
			     {
						for(var j=0;j<jsondata.total;j++){
							if(idArray[i]==jsondata.rows[j].loan_id){
								jQuery.messager.alert("提示","此"+j+"行,借款单已经存在，不能重复添加！");
								return false;
							}
						}
			    	 addRow(idArray[i],gdCodeArray[i],gdNameArray[i],person_nameArray[i],actual_operation_datesArray[i],moneysArray[i]);
			    	moneys+=parseFloat(moneysArray[i]);
			    	loan_money+=parseFloat(moneysArray[i]);
			     }
			    	 jQuery('#reimbursement').numberbox("setValue",moneys);
			    	 jQuery('#loan_money').numberbox("setValue",loan_money);
			    
			}
			function addRow(loan_id,gd_code,gd_name,person_name,actual_operation_date,money){
				jQuery('#table').datagrid('endEdit', lastIndex);
				jQuery('#table').datagrid('appendRow',{
					loan_id:loan_id,
					gd_name:gd_name,
					gd_code:gd_code,
					actual_operation_date:actual_operation_date,
					person_name:person_name,
					loan_money:money,
					money:money
				});
				var data = jQuery('#table').datagrid('getData');
				jQuery('#table').datagrid('loadData',data);
				lastIndex = jQuery('#table').datagrid('getRows').length-1;
				jQuery('#table').datagrid('selectRow', lastIndex);
				jQuery('#table').datagrid('beginEdit', lastIndex);
			}
			function reimMoney(){
				var money = 0;
				var loan_money = 0;
				var jsondata=jQuery("#table").datagrid("getData");
				for(var i=0;i<jsondata.total;i++){
					var row = jsondata.rows[i];
					if(row.money == null  || row.money == '' ){
						continue;
					}
					money += parseFloat(row.money);
					loan_money += parseFloat(row.loan_money);
				}
				jQuery('#reimbursement').numberbox("setValue",money);
				jQuery('#loan_money').numberbox("setValue",loan_money);
			}
		</script>
	</head>
	<body >
							<form id="lv"  method="post">
						<div style="width:90%;padding-left:50px;margin-top:20px" align="center">
							<table  style="border-collapse: collapse;" border="1px" width="100%" bordercolor="#0eb83a" >
							<tr>
								<td align="right" class="td1" nowrap>项目编号：</td>
								<td class="td2" nowrap>
									<input type="hidden" id="xm_id" name="xm_id"  value=""/>
									<input  id="xm_code" name="xm_code" readonly="readonly"  class="easyui-validatebox" data-options="required:true"  onclick="choseXm();" placeholder="项目验收后报账停止">
									<a href="javascript:void(0)" class="easyui-linkbutton" data-options="iconCls:'icon-add',plain:false" onclick="choseXm();"></a>								</td>
								<td align="right" class="td1" nowrap>项目名称：</td>
								<td class="td2" nowrap>
									<input  id="xm_name" name="xm_name" readonly="readonly"  class="easyui-validatebox" data-options="required:true"  placeholder="项目验收后报账停止">
								</td>
							</tr>
							<tr>
								
								<td align="right" class="td1" nowrap>经办人：</td>
								<td class="td2" nowrap >
									<input type="hidden"  id="creator_id" name="creator_id"  value="<%=person_id%>"/>
									<input  id="creator" name="creator" readOnly value="<%=person%>"  class="easyui-validatebox" data-options="required:true" />
								</td>
								<td align="right"  nowrap class="td1">
										报账日期：
									</td>
									<td class="td2" nowrap >
										<input id="operation_time" name="operation_time" class="easyui-datetimebox" data-options="required:true"/>
									</td>
							</tr>
								<tr>
									<td align="right"  nowrap class="td1">
										借款总额:
									</td>
									<td class="td2" nowrap >
											<input id="loan_money" name="loan_money" class="easyui-numberbox" readonly="readonly" data-options="min:0,precision:2,required:true" /><span>(自动计算)</span>
									</td>
									<td align="right"  nowrap class="td1">
										报账总额:
									</td>
									<td class="td2" nowrap >
											<input id="reimbursement" name="reimbursement" class="easyui-numberbox" readonly="readonly" data-options="min:0,precision:2,required:true" /><span>(自动计算)</span>
									</td>
								</tr>
								<tr>
									<td align="right"  nowrap class="td1">
										备注:
									</td>
									<td class="td2" nowrap colspan="3" >
							           <textarea id="remark" name="remark"  style="height:100%;width:98%" rows="6"></textarea>

									</td>
								</tr>
									<tr id="attaTr" style="display:none">
								      <td nowrap align="right" class="td1">附件明细: </td>
								      <td class="td2"  colspan="3" >
								        <input type="hidden" id="attachmentId" name="attachmentId">
								        <input type="hidden" id="attachmentName" name="attachmentName">
								        <span id="showAtt">
								        </span>
								      </td>
							   	    </tr>
								<tr>
							      <td nowrap align="right" class="td1">附件：</td>
							      <td class="td2"  colspan="3" >
							        	 <div id="fsUploadArea" class="flash" style="width:380px;">
										     <div id="fsUploadProgress"></div>
										     <div>
										       <input type="button" id="btnStart" class="SmallButtonW" value="开始上传" onclick="swfupload.startUpload();" disabled="disabled">&nbsp;&nbsp;
										       <input type="button" id="btnCancel" class="SmallButtonW" value="全部取消" onclick="javascript:swfupload.cancelQueue();jQuery('#fsUploadArea').hide();" disabled="disabled">&nbsp;&nbsp;
										    </div>
									      </div>
									      
										    <div id="attachment1">
									          <span id="spanButtonUpload" title="上传附件"></span>
									        </div>
							      </td>
					   		   </tr>
					   		   <%if(!"1".equals(isShow)){%>
					   		   <tr>
								<td align="right" nowrap class="td1">
								</td>
								<td  nowrap  colspan="3" >
								
									<a href="javascript:void(0)" class="easyui-linkbutton" data-options="iconCls:'icon-save',plain:false" onclick="doSubmit(this);">保存</a>
							
									<a href="javascript:void(0)" class="easyui-linkbutton" data-options="iconCls:'icon-cancel',plain:false" onclick="javascript:parent.window.close();">关闭</a>
								</td>
							</tr>
								<%} %>
								<tr>
										<td colspan="4"  nowrap>
											<div id="table"></div>
										</td>
								</tr>
				 			</table>
				 			</div>
				 			</form>
				 		
				 			
	</body>
</html>


